package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/service/inbox/api/internal/svc"
	"googee/service/inbox/api/internal/types"
	"googee/service/inbox/rpc/inbox"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type MessagelistLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMessagelistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MessagelistLogic {
	return &MessagelistLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MessagelistLogic) Messagelist(req *types.MessageListReq) (*types.MessageListReply, error) {
	logx.Infof("=====sssss >  \n")
	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	resp := &types.MessageListReply{}
	result, err := l.svcCtx.Inbox.GetList(l.ctx, &inbox.UserIdRequest{
		UserId: id,
		Offset: req.Offset,
		Limit:  req.Limit,
		Asc:    req.Asc,
	})

	logx.Infof("============== > error=%v \n", err)
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.InvalidArgument {
				return nil, errorx.NewCodeErrorNoMsg(errorx.INBOX_ERROR + 3)
			} else if st.Code() == errorx.UserNotExist {
				return nil, errorx.NewCodeErrorNoMsg(errorx.INBOX_ERROR + 2)
			} else {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}
	copier.Copy(&resp.Data, result.Messagelist)

	return resp, nil
}
